package com.ideal.hadoopadmin.common.util;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class JacksonUtil implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1867027251602633767L;
	private static final ObjectMapper mapper = new ObjectMapper();

	public JacksonUtil() {
		super();
	}
	
	/**
	 * @param <T>
	 *            娉涘瀷澹版槑
	 * @param bean
	 *            绫荤殑瀹炰緥
	 * @return JSON瀛楃涓�
	 */
	public <T> String toJson(T bean) {
		String jsonStr = "";
		try {
			jsonStr = mapper.writeValueAsString(bean);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return jsonStr;
	}

	/**
	 * @param <T>
	 *            娉涘瀷澹版槑
	 * @param json
	 *            JSON瀛楃涓�
	 * @param clzz
	 *            瑕佽浆鎹㈠璞＄殑绫诲瀷
	 * @return
	 */
	public <T> T fromJson(String json, Class<T> clzz) {
		T t = null;
		try {
			t = mapper.readValue(json, clzz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * @param <T>
	 *            娉涘瀷澹版槑
	 * @param json
	 *            JSON瀛楃涓�
	 * @param typereference
	 *            娉涘瀷瀵硅薄鐨勫尶鍚嶇被
	 * @return
	 */
	public <T> T fromJson(String json, TypeReference<T> typereference) {
		T t = null;
		try {
			t = mapper.readValue(json, typereference);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * @param json
	 *            JSON瀛楃涓�璇蜂繚鎸乲ey鏄姞浜嗗弻寮曞彿鐨�
	 * @return Map瀵硅薄,榛樿涓篐ashMap
	 */
	public Map<?, ?> fromJson(String json) {
		HashMap<?, ?> hmap = null;
		try {
			hmap = mapper.readValue(json, HashMap.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return hmap;
	}
	public static ObjectMapper getInstance(){
		
		return mapper;
	}
}
